<?php

namespace app\admin\controller\extend;
use app\common\controller\Backend;
use think\Db;
use think\Loader;

/**
 * 用户管理
 *
 * @icon fa fa-file-text-o
 */
class Users extends Backend
{
    /**
     * School模型对象
     */
    protected $searchFields = 'id,nick_name,phone,user_province';
    protected $model = null;
    protected $noNeedRight = ['cx_province_select','whitelist_del','whitelist_add','whitelist','sms_apply_list','sms_verify_success','sms_verify_fail','sms_verify','sms_content_editPost','sms_content_edit','sms_manage','set_black','month_province','look_data','get_goods','month_reg','user_clicks','login_clicks','user_logins','user_list_cj_city','user_list_citys','user_list_citys_daily','province_users','daily_views_province','daily_active_province','user_list_cj','cancel_vip'];
//    protected $noNeedLogin = ['update_user'];
    protected $isSuperAdmin = false;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\extend\Users();
        //是否超级管理员
        $this->isSuperAdmin = $this->auth->isSuperAdmin();
    }

    public function index()
    {
//        ini_set('max_execution_time', '0');
//        ini_set('memory_limit', '-1'); //内存 无限
//        $res=DB::name('test2')->select();
//        foreach ($res as $k=>&$v){
//            DB::name('school_z')->where(['id'=>$v['school_id']])->update(['alias_name'=>$v['name']]);
//        }
//        exit('ok');

//        cms_channel_school--院校栏目
//        $sql="select a.school_id,a.channel_id,b.province_id,count(*) nums from
//app_cms_archives a left join app_cms_archives_province b on
//a.id=b.archives_id where a.school_id>0 AND a.deletetime is NULL AND a.`status`='normal' AND b.province_id>0  group by a.school_id,b.province_id,a.channel_id ORDER BY school_id;";
//        $list= Db::query($sql);
//        DB::name('cms_channel_school_copy')->insertAll($list);
//        exit;



        //
//        $sql="
//select a.school_id,a.channel_id,a.`year`,count(*) num from
//app_cms_archives a  where a.school_id>0  AND a.`year`>2016 AND `year`<2023 AND a.deletetime is NULL AND a.`status`='normal' group by a.school_id,a.`year`,a.channel_id ORDER BY a.school_id,a.channel_id,a.`year`  limit 0,10000;";
//        $list= Db::query($sql);
//        foreach ($list as $k=>&$v){
//            $have=DB::name('channel_year')
//                ->field('id')
//                ->where(['school_id'=>$v['school_id'],'channel_id'=>$v['channel_id']])
//                ->find();
////            dump(DB::name('channel_year')->getLastSql());exit;
//            if ($have){
//                DB::name('channel_year')
//                    ->where(['id'=>$have['id']])
//                    ->update(['year_'.$v['year'].''=>$v['num']]);
//            }else{
//                DB::name('channel_year')->insert(['year_'.$v['year'].''=>$v['num'],'school_id'=>$v['school_id'],'channel_id'=>$v['channel_id']]);
//            }
//        }

//exit('ok');exit;

//        $sql="select a.school_id,a.channel_id,b.province_id,a.`year`,count(*) num from
//app_cms_archives a left join app_cms_archives_province b on
//a.id=b.archives_id where a.school_id>0 AND a.`year`>2016 AND `year`<2023 AND
// b.province_id>0 AND a.deletetime is NULL AND a.`status`='normal' AND a.channel_id=33
// group by a.school_id,a.channel_id,b.province_id,a.`year` order by a.school_id,a.channel_id,b.province_id,a.`year`;";
//        $list= Db::query($sql);
//        foreach ($list as $k=>&$v){
//            $have=DB::name('channel_province')
//                ->field('id')
//                ->where(['school_id'=>$v['school_id'],'channel_id'=>$v['channel_id'],'year'=>$v['year']])
//                ->find();
//            $py=DB::name('province')->field('py')->where(['id'=>$v['province_id']])->find()['py'];
//            if ($have){
//                DB::name('channel_province')
//                    ->where(['id'=>$have['id']])
//                    ->update([$py=>$v['num']]);
//            }else{
//                DB::name('channel_province')->insert([$py=>$v['num'],'school_id'=>$v['school_id'],'channel_id'=>$v['channel_id'],'year'=>$v['year']]);
//            }
//        }
////
//        exit('ok');


////        $time=strtotime(date("Y-m-d ",time()));
////        $end_time=$time+86400;
//       $sql="SELECT c.reg_ip, c.user_id,c.nick_name,c.`user_name`,c.phone ,city FROM app_zd_user_school_follow a LEFT JOIN app_school_z b ON a.school_id=b.id  LEFT JOIN app_zd_user c ON a.user_id=c.user_id WHERE a.create_time>1627437600  AND b.province_id=3 AND a.type=0 AND a.is_del=0  AND b.batch='专科'   GROUP BY a.user_id ";
//       $list= Db::query($sql);
////        $list=DB::name('zd_user')
////            ->field('city,user_id,phone,user_name,nick_name')
////            ->where("city regexp '泉州|漳州|福州|宁德|三明|南平|龙岩|莆田|厦门'")
////            ->where("candidates_identity NOT LIKE '%高职分类%' AND candidates_identity NOT LIKE '%报名%' AND user_province='福建'")
////            ->select();
//        $sql="SELECT b.reg_ip,b.user_name,b.nick_name,b.phone,b.user_id FROM app_zd_user_log_yjtj a LEFT JOIN app_zd_user b ON a.user_id=b.user_id WHERE a.create_time>1627437600 and a.sf like '%福建%' AND a.province='福建' AND a.user_id!='' GROUP BY a.user_id ";
//        $list= Db::query($sql);
//        dump($list);exit;
////        $data=DB::name('zd_user')
////            ->field('reg_ip,user_id,phone,user_name,nick_name')
////            ->where("city='' OR (city not like '%泉州%' and city not like '%龙岩%' and city not like '%福州%' and city not like '%宁德%' and city not like '%南平%' and city not like '%三明%' and city not like '%漳州%' and city not like '%莆田%' and city not like '%厦门%')")
////            ->where("candidates_identity NOT LIKE '%高职分类%' AND candidates_identity NOT LIKE '%报名%' AND user_province='福建'")
//////            ->limit(52001,3000)
////            ->select();
////        dump($data);exit;
//        $insert=[];
//        $a=0;
//        foreach ($list as $k=>&$v){
//            $have=DB::name('zd_user_fj_city')->where(['user_id'=>$v['user_id']])->find();
//            if (empty($have)){
//                $res=$this->get_city($v['reg_ip']);
//                $insert[$a]['city']='';
//                if(strpos($res,'泉州') !== false){
//                    $insert[$a]['city']='泉州';
//                }
//                if(strpos($res,'漳州') !== false){
//                    $insert[$a]['city']='漳州';
//                }
//                if(strpos($res,'厦门') !== false){
//                    $insert[$a]['city']='厦门';
//                }
//                if(strpos($res,'宁德') !== false){
//                    $insert[$a]['city']='宁德';
//                }
//                if(strpos($res,'三明') !== false){
//                    $insert[$a]['city']='三明';
//                }
//                if(strpos($res,'莆田') !== false){
//                    $insert[$a]['city']='莆田';
//                }
//                if(strpos($res,'龙岩') !== false){
//                    $insert[$a]['city']='龙岩';
//                }
//                if(strpos($res,'南平') !== false){
//                    $insert[$a]['city']='南平';
//                }
//                if(strpos($res,'福州') !== false){
//                    $insert[$a]['city']='福州';
//                }
//                $insert[$a]['user_id']=$v['user_id'];
//                $insert[$a]['phone']=$v['phone'];
//                $insert[$a]['user_name']=$v['user_name'];
//                $insert[$a]['nick_name']=$v['nick_name'];
//                if ($insert[$a]['city'])$a++;
//            }
//            }
//        DB::name('zd_user_fj_city')->insertAll($insert);
//        exit('ok');
//
//        exit('ok');
//        $str="year_2021";
//        $year=2021;
//        $channel_id=45;
//        $sql="SELECT count(*) ".$str.", school_id,channel_id
// FROM app_cms_archives WHERE deletetime is NULL AND
//  `year`=".$year." AND `from`<5 AND school_id>0 AND channel_id>0 GROUP BY school_id ,channel_id,`year` limit 14001,2000
//";
//    $sql="
//SELECT count(a.id) as nums,b.province_id,a.school_id FROM app_cms_archives  a LEFT JOIN app_cms_archives_province b ON a.id=b.archives_id
//WHERE a.`year`=".$year." AND a.channel_id=".$channel_id." and b.province_id>1 AND a.deletetime IS NULL AND school_id>0 GROUP BY a. school_id,b.province_id limit 0,2000";


//        exit('ok');

////
////        $sql="select a.school_id,a.channel_id,b.province_id,count(*) nums
//// from app_cms_archives a left join
////app_cms_archives_province b
////on a.id=b.archives_id where
////a.school_id>0 AND a.`year`>2016 AND a.channel_id!=45 AND a.deletetime is NULL group by a.school_id,b.province_id,channel_id;";
//        $list= Db::query($sql);
//        $a=0;
//        $arr=[];
//        $arr1=[];
//        $arr2=[];
//        $b=0;
//        $province = ["beijing","fujian","zhejiang","henan","anhui","shanghai","jiangsu","shangdong","jiangxi","chongqing","hunan","hubei","guangdong","guangxi","guizhou","hainan","sichuan","yunnan","shanxi","gansu","ningxia","qinghai","xinjiang","xizang","tianjin","heilongjiang","jilin","liaoning","hebei","sx","neimenggu"];
//
//        for ($i=0;$i<count($list);$i++){
//            if ($i==0){
//                $n=0;
//            }else{
//                $n=$i-1;
//            }
//            $school=$list[$n]['school_id'];
//            $s_id=$list[$i]['school_id'];
//            $c_id=$channel_id;
//            if ($school==$s_id){
//                $arr1[]=$list[$i]['province_id'];
//                $arr2[]=$list[$i]['nums'];
//            }else{
////                $province=['beijing'=>0,'shanghai'=>0,'fujian'=>0];
//                for ($d=0;$d<count($arr1);$d++){
//                    $py=DB::name('province')->field('py')->where(['id'=>$arr1[$d]])->find();
//                    $arr[$a][$py['py']]=$arr2[$d];
//                }
//
//                $arr3=array_intersect_assoc($province,$arr[$a]);
//                dump($arr3);exit;
//                $arr[$a]['school_id']=$school;
//                $arr[$a]['channel_id']=$c_id;
//                $arr[$a]['year']=$year;
//                $arr1=[];
//                $arr2=[];
//                $arr1[]=$list[$i]['province_id'];
//                $arr2[]=$list[$i]['nums'];
//                $a++;
////                DB::name("channel_province")->insert($arr);
//            }
//        }
//        dump($arr);exit;
//        for($n=0;$n<count($arr);$n++){
//            $res=DB::name("channel_province_copy")
//                ->where(['channel_id'=>$channel_id,'school_id'=>$arr[$n]['school_id'],'year'=>$year])->find();
//            if ($res){
//                unset($arr[$n]['school_id']);
//                unset($arr[$n]['channel_id']);
//                unset($arr[$n]['year']);
//                DB::name("channel_province_copy")->where(['channel_id'=>$channel_id,'school_id'=>$arr[$n]['school_id'],'year'=>$year])->update($arr[$n]);
//            }else{
//                DB::name("channel_province_copy")->insert($arr[$n]);
//            }
//        }
////        dump($arr);exit;
//      DB::name("channel_province")->insertAll($arr);
//        exit('ok');
//        dump($arr);exit;
////        $res=DB::name("channel_year")->insertAll($list);
//        foreach ($list as $k=>&$v){
//            $res=DB::name("channel_year")->where(['school_id'=>$v['school_id'],'channel_id'=>$v['channel_id']])->update([$str=>$v[$str]]);
//            if (!$res){
//                DB::name("channel_year")->insert(['school_id'=>$v['school_id'],'channel_id'=>$v['channel_id'],$str=>$v[$str]]);
//            }
//        }
//////
////
////        $res= array_chunk($list,3000,false);
//////
////        for ($i=0;$i<count($res);$i++){
////            DB::name('channel_year')->insertAll($res[$i]);
////        }
//        exit('ok');
//        $arr="12,14,15,17,21,23,24,25,26,27,28,29,30,31,33,37,39,40,41,42,43,45,46,48,49,51,56,57,60,68,69,70";
//        $data=DB::name('school_z')->field('id')->where('is_red=0')->limit(1)->order('province_id asc')->select();
//        $channel=DB::name('cms_channel')->field('id,p_type')->where("id IN (".$arr.")")->where("list_type='2' AND status='normal' AND type='list'")->select();
//        $pro=DB::name('province')->field('id')->where('id>1 and id<35')->select();
//        foreach ($data as $k=>&$v){
//            foreach ($channel as $key=>&$value){
//                if ($value['p_type']=='0'){
//                    $num=DB::name('cms_archives')->where("(channel_id=".$value['id']." OR channel_ids=".$value['id'].") and deletetime is null and year>0 and status='normal' and school_id=".$v['id']." ")->count();
//                    Db::name('cms_channel_school')->insert(['nums'=>$num,'school_id'=>$v['id'],'channel_id'=>$value['id'],'province_id'=>1]);
//                }else{
//                    foreach ($pro as $k1=>&$v1){
//                        $num=DB::name('cms_archives')->where("FIND_IN_SET(province,".$v1 ['id'].") and (channel_id=".$value['id']." OR channel_ids=".$value['id'].") and deletetime is null and year>0 and status='normal' and school_id=".$v['id']."  ")->count();
//                        Db::name('cms_channel_school')->insert(['nums'=>$num,'school_id'=>$v['id'],'channel_id'=>$value['id'],'province_id'=>$v1['id']]);
//                    }
//                }
//            }
//            DB::name('school_z')->where(['id'=>$v['id']])->update(['is_red'=>1]);
//        }
//        header("refresh: 0");

        $this->request->filter(['strip_tags', 'trim']);
//        dump(session());exit;
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
//            $this->relationSearch = true;
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
//            $total=$this->model->where($where)->count();
//            dump($where);exit;
//            $sql=
//            $res = $this->model
//                ->alias('m')
//                ->field('m.*,b.order_num,b.total_money')
//                ->join("(SELECT count(*) as order_num ,sum(payment_money) as total_money , user_id as order_user
//                FROM app_zd_order_master where order_status='1' group by user_id) b",'m.user_id=b.order_user','left')
//                ->limit($offset, $limit)
//                ->select();
//            $list=Db::table($res.' k')
//                ->field('k.*,a.end_time,IFNULL(all_vip_type, 0) as all_vip_type ')
//                ->join("(SELECT user_id as user,end_time,
//                 group_concat(vip_type ORDER BY vip_type ASC ) as all_vip_type FROM app_zd_user_vip_list
//                 where  end_time >".time()." group by user_id order by end_time asc) a" ,'k.user_id=a.user','left')
//                ->where($where)
//                ->order($sort, $order)
//                ->select();
            $where_new ='';
            $s_id=input('s_id');
            if($s_id) $where_new =   "m.middle_school_id=".$s_id."";
            $where_con = [];
           // $this->auth->username ='13635261210';
            if($this->auth->username == '13635261210'){
                $where_con = [
                    'graduation'=>['>=',2022]
                ];
            }
            $count= $this->model
                ->alias('m')
                ->join("(SELECT user_id as user,MAX(end_time) as end_time, group_concat(distinct type ORDER BY type ASC ) as all_type,
                group_concat( distinct vip_type ORDER BY vip_type ASC ) as all_vip_type FROM app_zd_user_vip
                 where end_time >".time()." AND is_del=0 group by user_id order by end_time desc) a" ,'m.user_id=a.user','left')
                ->join("(SELECT count(*) as order_num ,sum(payment_money) as total_money , user_id as order_user 
                FROM app_zd_order_master where order_status='1' AND is_del=0 AND order_id>40 group by user_id ) b",'m.user_id=b.order_user','left')
                ->where($where)
                ->where($where_new)
                ->where($where_con)
                ->where('m.is_cancel=0')
                ->count();
            $list = $this->model
                ->alias('m')
                ->field('m.*,IFNULL(a.all_vip_type, 1) as all_vip_type,a.all_type,a.end_time,b.order_num,b.total_money')
//                ->join('school_bind b','b.user_id=m.user_id','left')
                ->join("(SELECT user_id as user,MAX(end_time) as end_time, group_concat(distinct type ORDER BY type ASC ) as all_type,
                group_concat( distinct vip_type ORDER BY vip_type ASC ) as all_vip_type FROM app_zd_user_vip
                 where end_time >".time()." AND is_del=0 group by user_id order by end_time desc) a" ,'m.user_id=a.user','left')
                ->join("(SELECT count(*) as order_num ,sum(payment_money) as total_money , user_id as order_user 
                FROM app_zd_order_master where order_status='1' AND is_del=0 AND order_id>40 group by user_id ) b",'m.user_id=b.order_user','left')
                ->where($where)
                ->where($where_new)
                ->where($where_con)
                ->where('m.is_cancel=0')
                ->order($sort, $order)
                ->limit($offset,$limit)
                ->select();
            $sql = $this->model->getLastSql();
            $bind_info = Db::name('school_bind')->where('is_del=0 AND status<>2')->group('user_id,status')->field('status,user_id')->select();
            $bind_arr = [];
            foreach ($bind_info as $ww=>$vv){
                $bind_arr[$vv['user_id']] = $vv['status'];
            }
            foreach ($list as $w=>&$v){
                if(isset($bind_arr[$v['user_id']])){
                    $v['dealing'] = 1;
                    $v['b_status'] = $bind_arr[$v['user_id']];
                }else{
                    $v['dealing'] = 0;
                    $v['b_status'] = $v['crowd']==0?0:1;
                }
                if($this->auth->username != '13635261210'){
                    $list[$w]['phone']=hide_mobile($list[$w]['phone']);
                }else{
                    $list[$w]['phone']= $list[$w]['phone'];
                }

            }
            $time=strtotime(date("Y-m-d ",time()));
            $end_time=$time+86400;
            $today_reg = $this->model
                ->where("reg_time>=".$time." AND reg_time<".$end_time."")
                ->cache(500)
                ->count();
            $menus=controller('extend.Redisdata');
            $click=$menus->get_daliy_ip();
//              $click['click']=1;$click['click_pv']=12;
            $result = array("total" => $count,"sql"=>$sql, "rows" =>$list,"extend" => ['reg' => $today_reg, 'login' => 0,'click'=>$click['click'],'pv'=>$click['click_pv']]);
//            $result = array("total" => 100, "rows" => $list,"extend" => ['reg' => $today_reg, 'login' => 0,'click'=>$click['click'],'pv'=>$click['click_pv']]);
            return json($result);
        }
        $this->assignconfig('username',$this->auth->username);
        return $this->view->fetch();
    }

    /**
     * 生成查询所需要的条件,排序方式
     * @param mixed   $searchfields   快速查询的字段
     * @param boolean $relationSearch 是否关联查询
     * @return array
     */
    protected function buildparams($searchfields = null, $relationSearch = null)
    {

        $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
        $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
        $search = $this->request->get("search", '');
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        if(request()->controller()=='Extend.datas'){
            $sort=$this->request->get("sort");
        }else{
            $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
        }


//        dump($this->model->getPk());exit;
//        $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
//        $sort='id';
        $order = $this->request->get("order", "DESC");
        $offset = $this->request->get("offset/d", 0);
        $limit = $this->request->get("limit/d", 999999);
        //新增自动计算页码

        $page = $limit ? intval($offset / $limit) + 1 : 1;
        if ($this->request->has("page")) {
            $page = $this->request->get("page/d", 1);
        }
        $this->request->get([config('paginate.var_page') => $page]);
        $filter = (array)json_decode($filter, true);
        if (strtolower(request()->action())=='wx_article'){
            if (isset($filter['status'])){
                if ($filter['status']=='3')$filter['status']='1';
            }
        }
        $op = (array)json_decode($op, true);
        $filter = $filter ? $filter : [];
        $where = [];
        $alias = [];
        $bind = [];
        $name = '';
        $aliasName = '';

        if (!empty($this->model) && $this->relationSearch) {
            $name = $this->model->getTable();
            $alias[$name] = Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
            $aliasName = $alias[$name] . '.';
        }
        $sortArr = explode(',', $sort);
        foreach ($sortArr as $index => & $item) {
            $item = stripos($item, ".") === false ? $aliasName . trim($item) : $item;
        }
        unset($item);
        $sort = implode(',', $sortArr);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $where[] = [$aliasName . $this->dataLimitField, 'in', $adminIds];
        }
        if ($search) {
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
            foreach ($searcharr as $k => &$v) {
                $v = stripos($v, ".") === false ? $aliasName . $v : $v;
            }
            unset($v);
            $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
        }
        $index = 0;
        foreach ($filter as $k => $v) {
            if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $k)) {
                continue;
            }
            $sym = isset($op[$k]) ? $op[$k] : '=';
            if (stripos($k, ".") === false) {
                $k = $aliasName . $k;
            }
            $v = !is_array($v) ? trim($v) : $v;
            $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
            //null和空字符串特殊处理
            if (!is_array($v)) {
                if (in_array(strtoupper($v), ['NULL', 'NOT NULL'])) {
                    $sym = strtoupper($v);
                }
                if (in_array($v, ['""', "''"])) {
                    $v = '';
                    $sym = '=';
                }
            }

            switch ($sym) {
                case '=':
                case '<>':
                    if($k=='middle_school_id'){
                        $where[] = [$k, 'IN', is_array($v) ? $v : explode(',', $v)];
                        break;
                    }
                    $where[] = [$k, $sym, (string)$v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
                    break;
                case '>':
                case '>=':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'FINDIN':
                case 'FINDINSET':
                case 'FIND_IN_SET':
                    $v = is_array($v) ? $v : explode(',', str_replace(' ', ',', $v));
                    $findArr = array_values($v);
                    foreach ($findArr as $idx => $item) {
                        ///特殊处理
                        if($k=='all_vip_type' && $item==1){
                            $where[] = [$k, 'NULL'];
                        }else{
                            $bindName = "item_" . $index . "_" . $idx;
                            $bind[$bindName] = $item;
                            $where[] = "FIND_IN_SET(:{$bindName}, `" . str_replace('.', '`.`', $k) . "`)";
                        }
                    }
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'BETWEEN' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $tableArr = explode('.', $k);
                    if (count($tableArr) > 1 && $tableArr[0] != $name && !in_array($tableArr[0], $alias) && !empty($this->model)) {
                        //修复关联模型下时间无法搜索的BUG
                        $relation = Loader::parseName($tableArr[0], 1, false);
                        $alias[$this->model->$relation()->getTable()] = $tableArr[0];
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' TIME', $arr];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
            $index++;
        }
        if (!empty($this->model)) {
            $this->model->alias($alias);
        }
        $model = $this->model;
        $where = function ($query) use ($where, $alias, $bind, &$model) {
            if (!empty($model)) {
                $model->alias($alias);
                $model->bind($bind);
            }
            foreach ($where as $k => $v) {
                if (is_array($v)) {
                    call_user_func_array([$query, 'where'], $v);
                } else {
                    $query->where($v);
                }
            }
        };
        return [$where, $sort, $order, $offset, $limit, $page, $alias, $bind];
    }

    public function order_num(){  //各省会员数
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $id=input('ids');
            $list = Db::name('zd_order_master')
                ->alias('m')
                ->field("m.payment_money,m.order_sn,m.pay_time,a.goods_name,a.goods_num,a.sale_price")
                ->join('zd_order_detail a',"a.order_sn=m.order_sn",'left')
                ->where("m.user_id='".$id."' AND m.order_status='1' AND m.is_del=0 AND m.order_id>40")
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
//            dump($list);exit;
            $result = array("total" => count($list), "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();

    }
    public function look_data(){  //会员资料
        $this->request->filter(['strip_tags']);
        $id=input('ids');

        $user=Db::name('zd_user')
            ->alias('a')
            ->where('a.user_id="'.$id.'"')
            ->field('a.*,IFNULL(b.order_num, 0) as order_num,IFNULL(b.total_money, 0) as total_money')
            ->join("(SELECT count(*) as order_num ,sum(payment_money) as total_money , user_id as order_user 
                FROM app_zd_order_master where order_status='1' AND is_del=0 AND order_id>40 group by user_id ) b",'a.user_id=b.order_user','left')
            ->find();

        //认证信息
        $verify_info = $this->verifyInfo($id);

        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $type=input('type')?input('type'):0;
            if ($type==1){
                $count= DB::name('zd_user_vip')
                    ->alias('a')
                    ->field('a.*,b.user_name,b.nick_name,b.register_type')
                    ->join('zd_user b','a.user_id=b.user_id','left')
                    ->where("a.user_id='".$id."'")
                    ->count();
                $list= DB::name('zd_user_vip')
                    ->alias('a')
                    ->field('a.*,b.user_name,b.nick_name,b.register_type')
                    ->join('zd_user b','a.user_id=b.user_id','left')
                    ->where("a.user_id='".$id."'")
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset,$limit)
                    ->select();
                //填报会员处理
                $tb_info=Db::connect("database_zy")->table('data_user_fs')
                    ->where(['user_id'=>$id,'is_del'=>0])
                    ->column('km,ck_fs','sf');
                foreach($list as $k => &$v){
                    if($v['vip_type']==3){
                        $province_name = Db::name('province')->where(['id'=>$v['province_id']])->value('name');
                        $v['tb_sf']=isset($tb_info[$province_name]['sf'])?$tb_info[$province_name]['sf']:'-';
                        $v['tb_km']=isset($tb_info[$province_name]['km'])?$tb_info[$province_name]['km']:'-';
                        $v['tb_ck_fs']=isset($tb_info[$province_name]['ck_fs'])?$tb_info[$province_name]['ck_fs']:'-';
                    }else{
                        $v['tb_sf']='-';
                        $v['tb_km']='-';
                        $v['tb_ck_fs']='-';
                    }
                }
                $result = array("total" =>$count, "rows" => $list);
                return json($result);
            }
            if ($type==2){
                $list= DB::name('zd_order_master')
                    ->alias('a')
                    ->field('a.*,b.goods_name,b.goods_type')
                    ->join('zd_order_detail b','a.order_sn = b.order_sn','left')
                    ->where("a.user_id='".$id."'")
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);
                $result = array("total" => $list->total(), "rows" => $list->items());
                return json($result);
            }
            $list =  $list = $this->model
                ->where("user_id='".$id."'")
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $result = array("total" => 1, "rows" => $list);
            return json($result);
        }
        $tag_info = Db::name('zd_user_tag')->group('tag_id')->field('tag_id')->select();
        $vip_info = $this->get_vip($id);

        $this->assignconfig('id',$id);
        $this->assign('user',$user);
        $this->assign('verify_info',$verify_info);
        $this->assign('tag_info',$tag_info);
        $this->assign('vip_info',$vip_info);
        return $this->view->fetch();
    }

    //认证信息
    public function verifyInfo($id){
        $user= Db::name('zd_user')
            ->where(['user_id'=>$id,'is_cancel'=>0,'is_hacker'=>0])
            ->field('type,crowd,school,middle_school,department,duty,identity')
            ->order('id desc')
            ->find();
        $re= Db::name('school_bind')
            ->where('user_id="'.$id.'" AND is_del=0 AND status<>"2"')
            ->field('school,middle_school,user_type,department,duty,identity,status')
            ->order('id desc')
            ->find();
        //有处理中
        if($re){
            //数据不全补齐特殊处理
            if($re['status']==1 && ($user['department']=='' ||$user['duty']==''||$user['identity']=='')){
                Db::name('zd_user')->where(['user_id'=>$id])->update(['department'=>$re['department'],'duty'=>$re['duty'],'identity'=>$re['identity']]);
            }
            if($re['user_type'] == 1 || $re['user_type'] == 2){
                return [
                    'dealing'=>1,
                    'status'=>$re['status'],
                    'school_name'=>$re['middle_school'],
                    'identity'=>$re['identity']
                ];
            }else{
                return [
                    'dealing'=>1,
                    'status'=>$re['status'],
                    'school_name'=>$re['school'],
                    'identity'=>$re['identity']
                ];
            }
        }
        //无处理中
        else{
            if($user['type'] == 1 || $user['type'] == 2){
                return [
                    'dealing'=>0,
                    'status'=>$user['crowd']==0?0:1,
                    'school_name'=>$user['middle_school'],
                    'identity'=>$user['crowd']==1?'学生':($user['crowd']==2?'家长':'其他')
                ];
            }else{
                return [
                    'dealing'=>0,
                    'status'=>$user['crowd']==0?0:1,
                    'school_name'=>$user['school'],
                    'identity'=>$user['crowd']==1?'学生':($user['crowd']==2?'家长':'其他')
                ];
            }
        }
    }

    //获取会员
    public function get_vip($id){
        //五查会员
        $time=time();
        $where['crowd']=2;//20220530后全部为2
        $where['user_id']=$id;
        $where['is_del']=0;
        $where['vip_type']=2;
        $time_wucha=Db::name('zd_user_vip')
            ->where($where)
            ->order('id desc')
            ->limit(1)
            ->value('end_time');
        if($time_wucha){
            if($time_wucha>$time){
                //生效中
                $data['wucha']['is_vip']=1;
                $data['wucha']['vip_time']=$time_wucha;
                if(($time_wucha-$time)>15552000){
                    $data['wucha']['vip_time_length']='年';
                }else{
                    $data['wucha']['vip_time_length']='月';
                }
                $data['wucha']['vip_time_type']='已开通';
            }else{
                //过期
                $data['wucha']['is_vip']=0;
                $data['wucha']['vip_time_type']='已过期';
                //$data['wucha']['vip_time']=ceil(($time-$time_wucha)/(3600*24));
                $data['wucha']['vip_time']=$time_wucha;
                $data['wucha']['vip_time_length']='';
            }
        }else{
            $data['wucha']['is_vip']=0;
            $data['wucha']['vip_time_type']='未开通';
            $data['wucha']['vip_time']=0;
            $data['wucha']['vip_time_length']='';
        }
        unset($where['crowd']);

        //填报会员
        $where['vip_type']=3;
        $time_tianbao=Db::name('zd_user_vip')
            ->where($where)
            ->order('id desc')
            ->limit(1)
            ->value('end_time');
        if($time_tianbao){
            if($time_tianbao>$time){
                $data['tianbao']['is_vip']=1;
                $data['tianbao']['vip_time_type']='已开通';
            }else{
                $data['tianbao']['is_vip']=0;
                $data['tianbao']['vip_time_type']='已过期';
            }
            $data['tianbao']['vip_time']=$time_tianbao;
        }else{
            $data['tianbao']['vip_time_type']='未开通';
            $data['tianbao']['is_vip']=0;
            $data['tianbao']['vip_time']=0;
        }
        //陪伴会员
        $where=[];
        //$where['a.crowd']=$this->crowd;
        $where['a.user_id']=$id;
        $where['a.is_del']=0;
        $where['a.end_time']=['gt',$time];
        $where['a.vip_type']=4;
        $teacher_vip=Db::name('zd_user_vip')
            ->alias('a')
            ->join('app_zd_teacher_vip b','a.teacher_id=b.id','left')
            ->field('b.teacher_head_image,b.teacher_name,b.id teacher_id')
            ->where($where)
            ->order('a.id desc')
            ->select();
        //$data['sql']=Db::name('zd_user_vip')->getLastSql();
        $data['teacher_vip_list']=$teacher_vip;
        $teacher_vip_num=count($teacher_vip);
        if($teacher_vip_num){
            $time_tianbao=Db::name('zd_user_vip')
                ->alias('a')
                ->where($where)
                ->order('a.id desc')
                ->limit(1)
                ->value('a.end_time');
            if($time_tianbao>$time){
                $data['peiban']['vip_time_type']='已开通';
                $data['peiban']['is_vip']=1;
            }else{
                $data['peiban']['vip_time_type']='已过期';
                $data['peiban']['is_vip']=0;
            }
            $data['peiban']['vip_num']=$teacher_vip_num;
            $data['peiban']['vip_time']=$time_tianbao;
        }else{
            $data['peiban']['vip_time_type']='未开通';
            $data['peiban']['is_vip']=0;
            $data['peiban']['vip_num']=0;
            $data['peiban']['vip_time']=0;
        }
        return $data;
    }

    public function give_list(){
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $con['m.is_del']=0;
            $total = DB::name("zd_user_give")
                ->alias('m')
                ->where($where)
                ->where($con)
                ->count();
            $list = DB::name("zd_user_give")
                ->alias('m')
                ->field('m.*,a.nick_name as user_name,a.phone')
                ->join('zd_user a','a.user_id=m.user_id','left')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
//            dump($list);exit;
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }
    public function month_reg(){
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $year=date('Y');
            $total = $this->model
                ->field(" FROM_UNIXTIME(reg_time,'%Y-%m') as month")
                ->group('month')
                ->count();

            $list = $this->model
                ->alias('m')
                ->field("reg_time as id,FROM_UNIXTIME(m.reg_time,'%Y-%m') as month,count(m.id) as total_num,sum(case when candidates_identity='春季高考' then 1 else 0 end) as spring_num,sum(case when candidates_identity='都已报名' then 1 else 0 end) as all_num")
                ->group('month')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }



    public function month_province(){
        $this->request->filter(['strip_tags']);
        $this->searchFields = 'province';
        if ($this->request->isAjax()) {

            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $month=input('month');
            if($month){
                $startDay=$month. '-1';
                $endDay=$month. '-' . date('t', strtotime($startDay));
            }else{
                $thismonth = date('m');
                $thisyear = date('Y');
                $startDay = $thisyear . '-' . $thismonth . '-1';
                $endDay = $thisyear . '-' . $thismonth . '-' . date('t', strtotime($startDay));
            }
            $start_time= strtotime($startDay);//当前月的月初时间戳
            $end_time = strtotime($endDay)+86400;//当前月的月末时间戳


            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->where("reg_time>=".$start_time." AND reg_time<".$end_time."")
                ->group('user_province')
                ->count();

            $list = $this->model
                ->field("province,count(id) as total_num,sum(case when candidates_identity='春季高考' then 1 else 0 end) as spring_num,sum(case when candidates_identity='都已报名' then 1 else 0 end) as all_num")
                ->where("reg_time>=".$start_time." AND reg_time<".$end_time."")
                ->where('province !=""')
                ->group('province')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
//            dump($this->model->getLastSql());exit;
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();

    }


    public function province_users(){  //各省会员数
        $this->searchFields = 'province';
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {

            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $count = $this->model
                ->alias('u')
                ->join('zd_user_tag tag','tag.user_id = u.user_id','left')
                ->where($where)
                ->group('province')
                ->count();
            $time= time();
            /*
             *           sum(case when v.end_time>{$time} and vip_type =2 then 1 else 0 end) as wc_vip_num,
//                sum(case when v.end_time>{$time} and v.end_time is not null then 1 else 0 end) as vip_all,
//                sum(case when v.end_time>{$time} and vip_type =3 then 1 else 0 end) as tb_vip_num,
//                sum(case when v.end_time>{$time} and vip_type =4 then 1 else 0 end) as pb_vip_num,
//                //                sum(case when tag_id=1 then 1 else 0 end) as tag_common,
////                sum(case when tag_id=2 then 1 else 0 end) as tag_spring,
////                sum(case when tag_id=3 then 1 else 0 end) as tag_art,
////                sum(case when tag_id=4 then 1 else 0 end) as tag_sports,
////                sum(case when tag_id=5 then 1 else 0 end) as tag_special,
             */
            $list = $this->model
                ->alias('u')
                ->join('province p','p.name = u.province','left')
                //     ->join('zd_user_vip v','v.user_id = u.user_id','left')
                ->field("province,count(u.id) as total_num,p.id as province_id,
                sum(case when candidates_identity='春季高考' then 1 else 0 end) as spring_num,
                sum(case when candidates_identity='都已报名' then 1 else 0 end) as all_num")
                ->where($where)
                ->group('province')
                ->order($sort, $order)
                ->limit($offset,$limit)
                ->select();
            $tag_arr = [];
            $tag_info = Db::name('zd_user_tag')->group('province_id,tag_id')->field('count(*) as num,province_id,tag_id')->select();
            foreach ($tag_info as $taw =>$tav){
                $tag_arr[$tav['province_id']][$tav['tag_id']] = $tav['num'];
            }
            $vip_arr = [];
            $vip_info = Db::name('zd_user_vip')->where(['end_time'=>['>',time()]])->group('province_id,vip_type')->field('count(*) as num,province_id,vip_type')->select();
            foreach ($vip_info as $vipw =>$vipv){
                $vip_arr[$vipv['province_id']][$vipv['vip_type']] = $vipv['num'];
            }
            $vip_arr_out = [];
            $vip_info_all = Db::name('zd_user_vip')->group('province_id,vip_type')->field('count(*) as num,province_id,vip_type')->select();
            foreach ($vip_info_all as $outw =>$outv){
                $vip_arr_out[$outv['province_id']][$outv['vip_type']] = $outv['num'];
            }
            foreach ($list as $w=>&$v){
                $v['tag_common'] = 0;
                $v['tag_spring'] = 0;
                $v['tag_art'] = 0;
                $v['tag_sports'] = 0;
                $v['tag_special'] = 0;
                if(isset($tag_arr[$v['province_id']][1])){
                    $v['tag_common'] = $tag_arr[$v['province_id']][1];
                }
                if(isset($tag_arr[$v['province_id']][2])){
                    $v['tag_spring'] = $tag_arr[$v['province_id']][2];
                }
                if(isset($tag_arr[$v['province_id']][3])){
                    $v['tag_art'] = $tag_arr[$v['province_id']][3];
                }
                if(isset($tag_arr[$v['province_id']][4])){
                    $v['tag_sports'] = $tag_arr[$v['province_id']][4];
                }
                if(isset($tag_arr[$v['province_id']][5])){
                    $v['tag_special'] = $tag_arr[$v['province_id']][5];
                }
                $v['wc_vip_num'] = 0;
                $v['pb_vip_num'] = 0;
                $v['tb_vip_num'] = 0;
                $v['vip_all'] = 0;
                if(isset($vip_arr[$v['province_id']][2])){
                    $v['wc_vip_num'] = $vip_arr[$v['province_id']][2];
                }
                if(isset($vip_arr[$v['province_id']][3])){
                    $v['tb_vip_num'] = $vip_arr[$v['province_id']][3];
                }
                if(isset($vip_arr[$v['province_id']][4])){
                    $v['pb_vip_num'] = $vip_arr[$v['province_id']][4];
                }
                $v['vip_all'] = $v['wc_vip_num'] +$v['pb_vip_num'] + $v['tb_vip_num'];
                $v['common_num'] = $v['total_num'] - $v['vip_all'];
                $v['all_wc'] = 0;
                $v['all_pb'] = 0;
                $v['all_tb'] = 0;
                if(isset($vip_arr_out[$v['province_id']][2])){
                    $v['all_wc'] = $vip_arr_out[$v['province_id']][2];
                }
                if(isset($vip_arr_out[$v['province_id']][3])){
                    $v['all_tb'] = $vip_arr_out[$v['province_id']][3];
                }
                if(isset($vip_arr_out[$v['province_id']][4])){
                    $v['all_pb'] = $vip_arr_out[$v['province_id']][4];
                }
                $v['all_num'] = $v['all_wc'] +$v['all_tb'] + $v['all_pb'];
                $v['out_vip'] = $v['all_num']-$v['vip_all'];
            }
            $result = array("total" => $count, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();

    }


    public function daily_views(){
//       dump( $this->ipToArea());
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $year=date('Y');
            $total = DB::name("zd_user_views")
                ->group('time')
                ->count();

            $list = DB::name("zd_user_views")
                ->alias('m')
                ->field(" *,FROM_UNIXTIME(m.time,'%Y-%m-%d') as time1")
                ->group('time')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->cache(3600)
                ->select();
            foreach ($list as $k=>&$v){
                $v['reg_user']=$this->model->where("reg_time>=".$v['time']." AND reg_time<".($v['time']+86400)."")->cache(3600)->count();
                $v['click_ip']=$v['no_user_clicks']+$v['user_clicks'];//访问ip
                $v['new_clicks']=$v['no_user_clicks']+$v['reg_user'];//新访客=未注册+今日已注册
                $v['reg_rate']=round($v['reg_user']*100/$v['new_clicks'],2);///注册率=今日注册/新访客
                $v['no_reg_rate']=round((100-$v['reg_rate']),2);//未注册率=今日未注册/新访客
            }

            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();

    }


    public function daily_views_province (){  //每日分省注册数
        $this->request->filter(['strip_tags']);

        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $time=input('time');

            $start_time= strtotime($time);//当前月的月初时间戳
            $end_time = $start_time+86400;//当前月的月末时间戳


            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->where("reg_time>=".$start_time." AND reg_time<".$end_time."")
                ->group('province')
                ->cache(3600)
                ->count();

            $list = $this->model
                ->field("user_province,count(id) as total_num")
                ->where("reg_time>=".$start_time." AND reg_time<".$end_time."")
                ->group('province')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->cache(3600)
                ->select();
//            dump($this->model->getLastSql());exit;
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    public function user_clicks(){ //本月点击汇总
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $id=input('ids');
            $total = Db::name('zd_user_log_'.date('Ym'))
                ->alias('m')
                ->where("m.user_id='".$id."'")
                ->group('url')
                ->count();
            $list = Db::name('zd_user_log_'.date('Ym'))
                ->alias('m')
                ->field("count(m.id) as num ,url,m.content")
//                ->join('zd_path a',"a.xcx_url=CONCAT('pages',m.url)",'left')
                ->where("m.user_id='".$id."'")
                ->group('url')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }
    public function user_logins(){
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $id=input('ids');
            $total = Db::name('zd_user_log_'.date('Ym'))
                ->field(" FROM_UNIXTIME(create_time,'%Y-%m-%d') as date")
                ->where("user_id='".$id."'")
                ->group('date')
                ->count();
            $list = Db::name('zd_user_log_'.date('Ym'))
                ->alias('m')
                ->field("user_id ,FROM_UNIXTIME(create_time,'%Y-%m-%d') as date,count(m.id) as total_num")
                ->where("user_id='".$id."'")
                ->group('date')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    } //每天点击数

    public function login_clicks(){ //本月当天点击记录
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $id=input('id');
            $time=input('time');
            $start_time=strtotime($time);

            $end_time = $start_time+86399;//当前月的月末时间戳
            $total = Db::name('zd_user_log_'.date('Ym'))
                ->alias('m')
                ->where("m.user_id='".$id."' AND m.create_time>=".$start_time." and m.create_time <".$end_time."")
                ->group('url')
                ->count();
            $list = Db::name('zd_user_log_'.date('Ym'))
                ->alias('m')
                ->field("count(m.id) as num ,url,m.content")
//                ->join('zd_path a',"a.xcx_url=CONCAT('pages',m.url)",'left')
                ->where("m.user_id='".$id."' AND m.create_time>=".$start_time." and m.create_time <".$end_time."")
                ->group('url')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    public function daily_active_province (){  //每日分省活跃数
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $time=input('time');
            $start_time= strtotime($time);//当前月的月初时间戳
            $end_time = $start_time+86400;//当前月的月末时间戳
//            $model="zd_daily_active_province";
            $model= DB::name('zd_daily_active_province');
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $model
                ->where("time=".$start_time."")
                ->group('province')
                ->count();

            $list = $model
                ->where("time=".$start_time."")
                ->group('province')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
//            dump($this->model->getLastSql());exit;
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    public function user_list_cj(){ //春季高考人数
//        dump($this->get_city('140.243.38.105'));exit;
//        $this->get_city(15159364959);exit;
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($where)
                ->where("candidates_identity regexp '高职分类|报名'")
                ->order($sort, $order)
                ->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    public function user_list_cj_city(){
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = DB::name("zd_user_cj_city")

                ->group('time')
                ->count();
            $list = DB::name("zd_user_cj_city")
                ->field("count(id) as nums,FROM_UNIXTIME(time,'%Y-%m-%d') as time")
                ->group('time')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();


            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        $count=DB::name("zd_user_cj_city")->group('user_id')->cache(600)->count();
        $this->assign('count',$count);
        return $this->view->fetch();
    }


    public function user_list_citys(){
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
//            dump($where);exit;
            $total = DB::name("zd_user_cj_city")
                ->where($where)
                ->group('user_id')
                ->count();
            $list = DB::name("zd_user_cj_city")
                ->alias('m')
                ->field('m.id,a.user_id,m.city,a.user_name,a.nick_name,a.head_image,a.phone,a.crowd,a.sex,a.school,
                a.score1,a.score2,a.clicks,a.logins,a.reg_time,a.last_time')
                ->join('zd_user a','a.user_id=m.user_id','left')
                ->group('m.user_id')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
//            dump($list);exit;
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }
    public function ipToArea($ip=""){
        $ip = '110.90.228.138';

        $content = file_get_contents("http://ip.taobao.com/service/getIpInfo.php?ip=".$ip);
        exit();
        $api="http://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query=".$ip."&co=&resource_id=6006";
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$api);
        curl_setopt($ch,CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_1);
//        curl_setopt($ch,CURLOPT_HTTPHEADER,C('IP138_TOKEN'));
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,3);
        $handles = curl_exec($ch);
        curl_close($ch);
        $handles= iconv('GB2312', 'UTF-8', $handles);
        $arr=json_decode($handles,true);
        return $arr;
        return $arr['data'][0]['location'];
    }
    public function user_list_citys_daily(){
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $time=input('time');
            $start_time= strtotime($time);
            $total = DB::name("zd_user_cj_city")
                ->where(['time'=>$start_time])
                ->group('user_id')
                ->count();
            $list = DB::name("zd_user_cj_city")
                ->alias('m')
                ->field('m.id,a.user_id,m.city,a.user_name,a.nick_name,a.head_image,a.phone,a.crowd,a.sex,a.school,
                a.score1,a.score2,a.clicks,a.logins,a.reg_time,a.last_time')
                ->join('zd_user a','a.user_id=m.user_id','left')
                ->where(['m.time'=>$start_time])
                ->group('m.user_id')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->cache(3600)
                ->select();
//            dump($list);exit;
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }
    public function get_city($ip){
        $result = @file_get_contents("http://ip.ws.126.net/ipquery?ip=".$ip);
        $list = mb_convert_encoding($result, 'UTF-8', 'UTF-8,GBK,GB2312,BIG5'); //解决中文乱码

//        dump($list);
//         $request = Request::instance();
//         $ip = $request->ip();
//        $response = @file_get_contents('http://ip.taobao.com/service/getIpInfo.php?ip='.$ip);
//        $result  = json_decode($response);
        return $list;
//        print_r($result);
//        $url="https://www.baifubao.com/callback?cmd=1059&callback=phone&phone=15159364959";
//         $url = "http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=15159364959";
//         $url="http://mobsec-dianhua.baidu.com/dianhua_api/open/location?tel=".$ip."";
//         $result = file_get_contents($url);
//         $result = json_decode($result,true);
//         dump($result);
//         return $url;

    }

    public function curl_get($url){

        $header = array(
            'Accept: application/json',
        );
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 0);
        // 超时设置,以秒为单位
        curl_setopt($curl, CURLOPT_TIMEOUT, 1);

        // 超时设置，以毫秒为单位
        // curl_setopt($curl, CURLOPT_TIMEOUT_MS, 500);

        // 设置请求头
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        //执行命令
        $data = curl_exec($curl);

        // 显示错误信息
        if (curl_error($curl)) {
            print "Error: " . curl_error($curl);
        } else {
            // 打印返回的内容
            curl_close($curl);
            return $data;
        }
    }

    public function give_vip(){
        if ($this->request->isPost()){
            $data=input('post.');
            $data['m_id']=session('admin.id');
            $data['admin_name']=session('admin.nickname');
            $data['time']=time();
            $goods=DB('zd_goods_sku')->field('tb_lb,crowd,sku_id,goods_id,sku_name,province_id,days,year,teacher_id')->where(['sku_id'=>$data['goods']])->find();
            $data['goods_type']=$goods['goods_id'];
            $data['sku_name']=$goods['sku_name'];
//            $result=1;
            $result =Db::name('zd_user_give')->insertGetId($data);
            if ($result) {
                $where['is_del']=0;
                $ins_g['province_id']=$where['province_id']=$ins['province_id']=$goods['province_id'];
                $ins_g['user_id']=$where['user_id']=$ins['user_id']=$data['user_id'];
                $ins['begin_time']=time();
                $ins['type']=5;
                $ins['create_time']=time();
                $ins['order_sn']=$result;
                $end_time=0;
                $ins['vip_type']=$goods['goods_id'];
                $where['vip_type']=2;
                switch ($goods['goods_id']){
                    case 2:  //五查会员
                        $ins['days']=$goods['days'];
                        $ins['end_time']=time()+($goods['days']*86400);
                        $end_time=$goods['days']*86400;
                        $ins['crowd']=$goods['crowd'];
                        $have=DB::name('zd_user_vip')->where($where)->where("end_time>".time()."")->find();
                        if ($have){
                            $ins['end_time']=((int)$have['end_time']+(int)$end_time);
                        }
//                        dump($end_time.'/'.$have['end_time'].'/'.$ins['end_time']);exit;
                        break;
                    case 3:  //模拟填报会员
                        $ins['end_time']=strtotime($goods['year'].'/09/1');
                        $ins['year']=$goods['year'];
                        $ins['tb_lb']=$goods['tb_lb'];
                        $ins_g['crowd']=2;
                        $ins_g['vip_type']=2;
                        $ins_g['days']=360;
                        $end_time=$ins_g['days']*86400;
                        $ins_g['begin_time']=time();
                        $ins_g['type']=5;
                        $ins_g['create_time']=time();
                        $ins_g['order_sn']=$result;
                        $ins_g['end_time']=time()+$end_time;
                        $have=DB::name('zd_user_vip')->where($where)->where("end_time>".time()."")->order('end_time desc')->find();
                        if ($have){
                            $ins_g['end_time']=((int)$have['end_time']+(int)$end_time);
                        }

                        break;
                    case 4:  //陪伴会员
                        $ins['teacher_id']=$goods['teacher_id'];
                        $ins['year']=$goods['year'];
                        $ins['end_time']=strtotime($goods['year'].'-09-1');
                        break;
                }
                $where = [];
                //   $where['type'] = 1;
                $where['is_out'] = 0;
                $where['vip_type'] = $ins['vip_type'];
                $where['province_id'] = $ins['province_id'];
                if($goods['goods_id'] == 2){
                    $where['crowd'] = $ins['crowd'];
                }
                $where['user_id'] = $ins['user_id'];
                Db::name('zd_user_vip')->where($where)->update(['is_out'=>1]);
                $res=DB::name('zd_user_vip')->insert($ins);
                if ($res && $goods['goods_id']==3){
                    $where = [];
                    //   $where['type'] = 1;
                    $where['is_out'] = 0;
                    $where['vip_type'] = $ins_g['vip_type'];
                    $where['province_id'] = $ins_g['province_id'];
                    $where['user_id'] = $ins_g['user_id'];
                    $where['crowd'] = $ins_g['crowd'];
                    Db::name('zd_user_vip')->where($where)->update(['is_out'=>1]);
                    DB::name('zd_user_vip')->insert($ins_g);
                }


//                if (!$info=DB::name('zd_user_vip_list')->where("vip_type=".$goods['goods_id']." AND user_id=".$data['user_id']."")->find()){
////                    DB::name('zd_user_vip_list')->insert(['user_id'=>$data['user_id'],'end_time'=>$ins['end_time'],'vip_type'=>$goods['goods_id']]);
////                }else{
////                    DB::name('zd_user_vip_list')
////                        ->where(['user_id'=>$data['user_id'],'vip_type'=>$goods['goods_id']])
////                        ->update(['end_time'=>$end_time+$ins['end_time']]);
////                }
                $this->success();
            } else {
                $this->error(__('操作失败'));
            }
        }
        $data=input('');
        $goods=DB::name('zd_goods')->field("id,goods_name")->where(['is_sale'=>1,'goods_type'=>2])->select();
        $pro=get_pro();
//        dump($data);exit;
        $this->assign('pro',$pro);
        $this->assign('goods',$goods);
        $this->assign('data',$data);
        return $this->view->fetch();
    }

    public function get_goods(){
        $good_id=input('good_id');
        $pro=input('pro');
        $where = [
            'promotion_id'=>0,
            'parent_sku_id'=>0,
            'is_del'=>0,
            'is_sale'=>1,
            'goods_id'=>$good_id,
            'province_id'=>$pro,
            'goods_type'=>2,
            'plan_cdkey'=>''
        ];
        if (empty($good_id))$this->error('错误');
        $res=DB::name('zd_goods_sku')
            ->field('sku_name,sku_id')
            ->where($where)
//            ->group('a.group_id')
            ->select();
        return ['code'=>1,'data'=>$res];
    }

    public function vip_config(){
        if ($this->request->isPost()){
            $data=input();
            $pro=$data['province'];
//            dump($data);exit;
            DB::name('zd_vip_config_wucha')->where('id>0')->update(['data_id'=>$data['row']['data_id'],'channel_id'=>$data['row']['channel_id'],'is_free'=>1,'free_days'=>$data['free_days1']]);
            $data['row']['is_free']=0;
            $data['row']['free_days']=$data['free_days'];
            for ($i=0;$i<count($pro);$i++){
                DB::name('zd_vip_config_wucha')->where(['province_id'=>$pro[$i]])->update($data['row']);
            }
            $this->success();
        }
        $pro=get_pro();
        $this->assign('pro',$pro);
        $row=DB::name('zd_vip_config_wucha')
            ->field('*,group_concat( province_id ORDER BY province_id ASC ) as province')
            ->where(['is_free'=>0])
            ->find();

        $row1=DB::name('zd_vip_config_wucha')
            ->field('free_days')
            ->where(['is_free'=>1])
            ->find();
//        dump(channel_list2());exit;
        $this->assign('row',$row);
        $this->assign('row1',$row1);
        $this->assignconfig('channelList',channel_list2());
        $this->assignconfig('searchList',get_data_type());
        $this->assignconfig('channel',explode(',',$row['channel_id']));
//        dump(explode(',',$row['data_id']));exit;
        $this->assignconfig('data',explode(',',$row['data_id']));
        return $this->view->fetch();

    }
    public function order_edit($ids=null){
        $data = Db::name('zd_user_vip')->where(['id'=>$ids])->field('id,province_id,vip_type')->find();

        $tb_info=[
            'tb_sf'=>input('tb_sf'),
            'tb_km'=>input('tb_km'),
            'tb_ck_fs'=>input('tb_ck_fs'),
            'tb_user_id'=>input('tb_user_id')
        ];

        $pro=get_pro();

        $this->assign('data',$data);
        $this->assign('pro',$pro);
        $this->assign('tb_info',$tb_info);
        return $this->view->fetch();
    }
    public function order_editPost(){
        $data=input();

        Db::name('zd_user_vip')->where(['id'=>$data['id']])->update(['province_id'=>$data['province_id']]);

        if(isset($data['tb_km'])){
            if($data['tb_km']==1){
                //清空科目和分数
                Db::connect("database_zy")->table('data_user_fs')
                    ->where(['user_id'=>$data['tb_user_id'],'sf'=>$data['tb_sf']])
                    ->update(['is_del'=>1]);
            }
//            else{
//                Db::connect("database_zy")->table('data_user_fs')
//                    ->where(['user_id'=>$data['tb_user_id'],'sf'=>$data['tb_sf']])
//                    ->update(['ck_fs'=>$data['tb_ck_fs']]);
//            }
        }

        $this->success();
    }
    public function cancel_vip(){
        $id=input('id');
        $phone=input('phone');
        $res=Db::name('zd_user_vip')->where(['id'=>$id])->update(['is_del'=>1]);

        if ($res){
            $m_id=session('admin.id');
            $m_name=session('admin.nickname');
            $data=Db::name('zd_user_vip')->where(['id'=>$id])->find();

            $give_data = [
                'send_type'=>3,
                'user_id'=>$data['user_id'],
                'province'=>$data['province_id'],
                'm_id'=>$m_id,
                'mark'=>'取消会员权益',
                'time'=>time(),
                'user_name'=>$phone,
                'goods_type'=>$data['vip_type'],
                'admin_name'=>$m_name,
            ];
            DB::name('zd_user_give')->insert($give_data);

            return ['code'=>1,'msg'=>'取消会员成功'];
        }else{
            return ['code'=>0,'msg'=>'取消会员失败'];
        }

    }

    public function set_black(){
        $user_id=input('user_id');
        $is_hacker=input('is_hacker');
        if ($is_hacker==2){
            $res=Db::name('zd_user')->where(['user_id'=>$user_id])->update(['is_hacker'=>0]);//2黑名单 移出
            $res2=Db::name('admin')->where(['user_id'=>$user_id])->update(['status'=>'normal']);//后台
            if ($res && $res2){
                return ['code'=>1,'msg'=>'移出黑名单成功'];
            }else{
                return ['code'=>0,'msg'=>'移出黑名单失败'];
            }
        }else{
            $res=Db::name('zd_user')->where(['user_id'=>$user_id])->update(['is_hacker'=>2]);//2黑名单 加入
            $res2=Db::name('admin')->where(['user_id'=>$user_id])->update(['status'=>'hidden']);//后台
            if ($res && $res2){
                return ['code'=>1,'msg'=>'加入黑名单成功'];
            }else{
                return ['code'=>0,'msg'=>'加入黑名单失败'];
            }
        }

    }

    public function sms_manage(){
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where_new ='';
            $s_id=input('s_id');
            if($s_id) $where_new =   "m.middle_school_id=".$s_id."";
            $count= $this->model
                ->alias('m')
                ->join("(SELECT user_id as user,MAX(end_time) as end_time, group_concat(distinct type ORDER BY type ASC ) as all_type,
                group_concat( distinct vip_type ORDER BY vip_type ASC ) as all_vip_type FROM app_zd_user_vip
                 where end_time >".time()." AND is_del=0 group by user_id order by end_time desc) a" ,'m.user_id=a.user','left')
                ->where($where)
                ->where($where_new)
                ->where('m.is_cancel=0')
                ->count();
            $ids_sql=Db::name('zd_user')
                ->alias('m')
                ->field('m.user_id')
                ->join("(SELECT user_id as user,group_concat( distinct vip_type ORDER BY vip_type ASC ) as all_vip_type FROM app_zd_user_vip where end_time >".time()." AND is_del=0 group by user_id order by end_time desc) a" ,'m.user_id=a.user','left')
                ->where($where)
                ->where($where_new)
                ->where('m.is_cancel=0')
                ->buildSql();

            $list = $this->model
                ->alias('m')
                ->field('m.id,m.graduation,m.user_id,m.province,m.city,m.region,m.nick_name,m.phone,m.type,m.reg_time,IFNULL(a.all_vip_type, 1) as all_vip_type')
                ->join("(SELECT user_id as user,group_concat( distinct vip_type ORDER BY vip_type ASC ) as all_vip_type FROM app_zd_user_vip where end_time >".time()." AND is_del=0 group by user_id order by end_time desc) a" ,'m.user_id=a.user','left')
                ->where($where)
                ->where($where_new)
                ->where('m.is_cancel=0')
                ->order($sort, $order)
                ->limit($offset,$limit)
                ->select();

            $result = array("ids_sql"=>$ids_sql,"total" => $count, "rows" =>$list);
            return json($result);
        }
        return $this->view->fetch();
    }

    public function sms_content_edit(){
        $ids_sql=input('ids_sql');
        $ids=Db::query($ids_sql);
        foreach($ids as &$vo){
            $vo = $vo['user_id'];
        }

        $total=count($ids);

        $this->assign('ids_sql',$ids_sql);
        $this->assign('total',$total);

        return $this->view->fetch();
    }

    public function sms_content_editPost(){
        $ids_sql = input('ids_sql');
        $sms_content = input('sms_content');
        $total = input('total');

        $m_id_from = session('admin.id');
        $m_name_from = session('admin.nickname');

        //插入申请表
        $data=[
            'sms_content'=>$sms_content,
            'total'=>$total,
            'create_time'=>time(),
            'm_id_from'=>$m_id_from,
            'm_name_from'=>$m_name_from
        ];
        $sms_apply_id=Db::name('zd_sms_apply')->insertGetId($data);

        //插入短信记录表
        $insert=[];
        $user_ids=Db::query($ids_sql);
        foreach($user_ids as $vo){
            array_push($insert,['user_id'=>$vo['user_id'],'sms_apply_id'=>$sms_apply_id]);
        }
        Db::name('zd_sms_apply_send_list')->insertAll($insert);

        $this->success();
    }

    public  function sms_apply_list(){
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = Db::name('zd_sms_apply')
                ->where($where)
                ->count();
            $list = Db::name('zd_sms_apply')
                ->alias('a')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }

        return $this->view->fetch();
    }

    public  function sms_verify(){
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = Db::name('zd_sms_apply')
                ->where($where)
                ->count();
            $list = Db::name('zd_sms_apply')
                ->alias('a')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }

        return $this->view->fetch();
    }

    public function sms_verify_success(){
        $id=input('id');
        $m_id = session('admin.id');
        $m_name = session('admin.nickname');

        $sms_apply=Db::name('zd_sms_apply')->where(['id'=>$id])->find();

        $phone_arr=Db::name('zd_sms_apply_send_list')
            ->alias('a')
            ->field('b.phone,a.id')
            ->join('zd_user b','a.user_id=b.user_id','left')
            ->where('a.sms_apply_id='.$id.' and status=0')
            ->select();

        $fail_num=0;
        $count=0;
        $phone='';
        $send_id_arr=[];
        $total=count($phone_arr);
        foreach($phone_arr as $vo){
            $count++;
            $phone=$phone.','.$vo['phone'];
            array_push($send_id_arr,$vo['id']);
            if($count==300 || $count==$total){
                $send_rs=send_sms($phone,$sms_apply['sms_content']);
                if ($send_rs['status'] <> 0){
                    $fail_num+=$count;
                }else{
                    Db::name('zd_sms_apply_send_list')->where(['id'=>['in',$send_id_arr]])->update(['status'=>1]);
                }
                $count=0;
                $send_id_arr=[];
                $phone='';
            }

        }

        if ($fail_num==0){
            Db::name('zd_sms_apply')->where(['id'=>$id])->update(['status'=>1,'m_id'=>$m_id,'m_name'=>$m_name,'fail_num'=>$fail_num]);
            return ['code'=>1,'msg'=>'审核并发送成功'];
        }else{
            Db::name('zd_sms_apply')->where(['id'=>$id])->update(['status'=>1,'m_id'=>$m_id,'m_name'=>$m_name,'fail_num'=>$fail_num]);
            return ['code'=>0,'msg'=>'审核并发送完成，失败'.$fail_num.'条'];
        }
    }

    public function sms_verify_fail(){
        $id=input('id');
        $m_id = session('admin.id');
        $m_name = session('admin.nickname');

        $res=Db::name('zd_sms_apply')->where(['id'=>$id])->update(['status'=>2,'m_id'=>$m_id,'m_name'=>$m_name]);

        if ($res){
            return ['code'=>1,'msg'=>'拒绝申请成功'];
        }else{
            return ['code'=>0,'msg'=>'拒绝申请失败'];
        }
    }

    public function whitelist(){
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = Db::name('zd_user_vip_whitelist')
                ->alias('a')
                ->join('zd_user b','a.user_id=b.user_id','left')
                ->where($where)
                ->where(['a.is_del'=>0,'b.is_cancel'=>0])
                ->count();
            $list = Db::name('zd_user_vip_whitelist')
                ->alias('a')
                ->field('a.id,a.user_id,a.m_name,a.create_time,a.desc,b.phone,b.nick_name,b.user_name')
                ->join('zd_user b','a.user_id=b.user_id','left')
                ->where($where)
                ->where(['a.is_del'=>0,'b.is_cancel'=>0])
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $sql= Db::name('zd_user_vip_whitelist')->getLastSql();


            $result = array("total" => $total, "rows" => $list, "sql" =>$sql);
            return json($result);
        }

        return $this->view->fetch();
    }

    public function whitelist_add(){
        if ($this->request->isPost()){
            $phone=input('post.phone/s');
            $user_id=Db::name('zd_user')->where(['phone'=>$phone,'is_cancel'=>0])->value('user_id');
            if(!$user_id){
                $this->error('未查询到该手机号用户');
            }
            $exist=Db::name('zd_user_vip_whitelist')->where(['user_id'=>$user_id,'is_del'=>0])->find();
            if($exist){
                $this->error('该手机号已经在白名单里，请勿重复添加');
            }

            $data['user_id']=$user_id;
            $data['create_time']=time();
            $data['m_id']=session('admin.id');
            $data['m_name']=session('admin.nickname');
            $data['desc']=input('post.desc/s');
            Db::name('zd_user_vip_whitelist')->insert($data);
            $this->success();
        }
        return $this->view->fetch();
    }

    public function whitelist_del($ids = ""){
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $re = Db::name('zd_user_vip_whitelist')->where(['id'=>$ids])->update(['is_del'=>1]);
            if ($re) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
    }

    /**
     * 联动搜索
     */
    public function cx_province_select()
    {
        $type = $this->request->get('type');
        $group_id = $this->request->get('group_id');
        $list = null;

        if ($type == 'province') {
            $where = [];
            $list = Db::name('province')->where($where)->field('id as value, name')->select();
        } else if($type == 'city'){
            $where = [
                'province_id' => $group_id,
                'is_del'=>0
            ];
            $list =  Db::name('province_city')->where($where)->field('id as value, city AS name')->select();
        } else if($type == 'region'){
            $where = [
                'city_id' => $group_id,
                'is_del'=>0
            ];
            $list =  Db::name('province_city_region')->where($where)->field('id as value, region AS name')->select();
        } else if($type == 'school'){
            $where = [
                'region_id' => $group_id,
            ];
            $list =  Db::name('zd_middle_school')->where($where)->field('id as value, school AS name')->select();
        }

        $this->success('', null, $list);
    }
}
